'''
Created on Apr 10, 2011

@author: AlexJ alexj@backpocket.com
'''
import urllib2
import cookielib
# import logging
import simplejson


class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError




class SubsonicJson:
    SelectionType = Enum(["random", "newest", "highest", "frequent", "recent"])
    
    
    def __init__(self, subsonic_server = "localhost", user = "user", password = "password", api_version = "1.1.0", app_name="SubsonicJson"):
        print "Server: %s" % subsonic_server
        self.cookiejar = cookielib.CookieJar()
        self.subsonic_server =subsonic_server
        self.user =user        
        self.password =password
        self.api_version=api_version
        self.app_name=app_name
        self.json_cmd = 0        
        # logging.basicConfig(level=logging.DEBUG)
        try:
            retval = self.ping()
            self.ready=True            
        except urllib2.URLError:
            print 'ERROR'
            self.ready=False


    def createUrl(self, method, args=[]):
        url = "http://%s/rest/%s?u=%s&p=%s&v=%s&c=%s&f=json" % (self.subsonic_server, method, self.user, self.password, self.api_version, self.app_name)
        for x in args:
            if x is not None:
                url= url+"&"+x
        print url 
        return url 
    
    
    def post(self, method, args=[]):
        url = self.createUrl(method, args)
        self.json_cmd += 1
        
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        resp = simplejson.load(response)
        return resp
        
              

        
    def ping(self):
        response = self.post("ping.view")
        return response['subsonic-response']

    def getLicense(self):
        response = self.post("getLicense.view")
        return response['subsonic-response']
    def getMusicFolders(self):
        response = self.post("getMusicFolders.view")
        return response['subsonic-response']
    def getNowPlaying(self):
        response = self.post("getNowPlaying.view")
        return response['subsonic-response']

    def getIndexes(self, musicFolderId=None, ifModifiedSince=None):
        args = []
        
        if musicFolderId is not None:
            args.append("musicFolderId=%s" % musicFolderId)
            
        if ifModifiedSince is not None:
            args.append("ifModifiedSince=%s" % ifModifiedSince)
            
        response = self.post("getIndexes.view", args)
        return response['subsonic-response']

    def getMusicDirectory(self, id):
        response = self.post("getMusicDirectory.view", ["id=%s" % id])
        return response['subsonic-response']

    def getPlaylist(self, id):
        response = self.post("getPlaylist.view", ["id=%s" % id])
        return response['subsonic-response']


    def createDownloadUrl(self, id):
        url = self.createUrl("download.view", ["id=%s" % id])
        return url

    def createStreamUrl(self, id, maxBitRate=None):
        args = []
        args.append("id=%s" % id)
        
        if maxBitRate is not None:
            args.append("maxBitRate=%s" % maxBitRate)
        
        url = self.createUrl("stream.view", args)
        return url


    def getCoverArt(self, id, size=None):
        args = []
        args.append("id=%s" % id)
        if size is not None:
            args.append("size=%s" % size)
        
        url = self.post("getCoverArt.view", args)
        return url


    def changePassword(self, username, password):
        response = self.post("changePassword.view", ["username=%s" % username, "password=%s" % password])
        return response['subsonic-response']
    
    def getUser(self, username):
        response = self.post("getUser.view", ["username=%s" % username])
        return response['subsonic-response']

    def deleteUser(self, username):
        response = self.post("deleteUser.view", ["username=%s" % username])
        return response['subsonic-response']


    def addChatMessage(self, message):
        response = self.post("addChatMessage.view", ["message=%s" % message])
        return response['subsonic-response']


    def getChatMessages(self,  since=None):
        args = []
        
        if since is not None:
            args.append("since=%s" % since)

        url = self.post("getChatMessages.view", args)
        return url



    def getAlbumList(self, type, size=None, offset=None):
        args = []
        args.append("type=%s" % type)
        if size is not None:
            args.append("size=%s" % size)

        if offset is not None:
            args.append("offset=%s" % offset)
        
        
        url = self.post("getAlbumList.view", args)
        return url



    def getRandomSongs(self, size=None, genre=None, fromYear=None, toYear=None, musicFolderId=None):
        args = []
        
        if size is not None:
            args.append("size=%s" % size)

        if genre is not None:
            args.append("genre=%s" % genre)
        
        if fromYear is not None:
            args.append("fromYear=%s" % fromYear)
        
        if toYear is not None:
            args.append("toYear=%s" % toYear)
        
        if musicFolderId is not None:
            args.append("musicFolderId=%s" % musicFolderId)
        
        
        url = self.post("getRandomSongs.view", args)
        return url




    def getLyrics(self, artist=None, title=None):
        args = []
        if artist is not None:
            args.append("artist=%s" % artist)

        if title is not None:
            args.append("title=%s" % title)
        
        
        url = self.post("getLyrics.view", args)
        return url




if __name__ == '__main__':
    app = SubsonicJson("XXXXX", "YYYY", "ZZZZZZZ")
    retval = app.ping()
    print retval
    
    retval = app.getLicense()
    print retval
    
    retval = app.getMusicFolders()
    print retval
    
    retval = app.getNowPlaying()
    print retval
    
    retval = app.getIndexes(1)
    print retval
    
    retval = app.getMusicDirectory('643a5c616374696f6e')
    print retval
    
    retval = app.createDownloadUrl('aaaa')
    print retval
    
    retval = app.createStreamUrl('aaaa', 128)
    print retval
    
    retval = app.createStreamUrl('aaaa')
    print retval

    retval = app.getAlbumList(SubsonicJson.SelectionType.random)
    print retval

    retval = app.getRandomSongs()
    print retval

    
    
        